%% @author author <author@example.com>
%% @copyright YYYY author.

%% @doc Web server for myapp.

-module(myapp_web).
-author('author <author@example.com>').

-export([start/1, stop/0, loop/2]).

%% External API

start(Options) ->
    {DocRoot, Options1} = get_option(docroot, Options),
    Loop = fun (Req) ->
                   ?MODULE:loop(Req, DocRoot)
           end,
    mochiweb_http:start([{max,1000000},{name, ?MODULE}, {loop, Loop} | Options1]).

stop() ->
    mochiweb_http:stop(?MODULE).

loop(Req, DocRoot) ->
	Socket = Req:get(socket),
	io:format("hello 1 ~p~n",[Socket]),
	log4erl:info("hello web"),
	Socket = Req:get(socket),
    ParentId = self(),
    gen_tcp:controlling_process(Socket, spawn(fun()-> controll(Socket, ParentId) end)),
    "/" ++ Path = Req:get(path),
    case Req:get(method) of
        Method when Method =:= 'GET'; Method =:= 'HEAD' ->
            case Path of
                "test/" ++ Id ->
                    Response = Req:ok({"text/html; charset=utf-8",
                                      [{"Server","myname-server"}],
                                      chunked}),
                    Response:write_chunk("Mochiconntest welcomes you! Your Id: " ++ Id ++ "\r\n"),

                    %% router:login(list_to_atom(Id), self()),
                    feed(Response,Id,1);
                  _->
                    Req:not_found()
            end;
        'POST' ->
            case Path of
                _ ->
                    Req:not_found()
            end;
        _ ->
            Req:respond({501, [], []})
    end.


   feed(Response, Path, N) ->
        receive
             %{router_msg, Msg} ->
             %    Html = io_lib:format("Recvd msg #~w: ‘~s’<br/>", [N, Msg]),
             %    Response:write_chunk(Html);
        after 1000 ->
              Msg = io_lib:format("Chunk ~w for id ~s \r\n<br>", [N, Path]),
              Response:write_chunk(Msg)
        end,
        feed(Response, Path, N+1).


%% Internal API

get_option(Option, Options) ->
    {proplists:get_value(Option, Options), proplists:delete(Option, Options)}.

controll(Socket, From)->
    log4erl:info("controlling process started~n"),
    case gen_tcp:recv(Socket, 0, 120000) of
        {error, timeout} ->
			log4erl:error("tcp error timeout ~n"),
            gen_tcp:controlling_process(Socket, From),
            loop_timeout(From);      		
        {error, Reason} ->
            log4erl:error("tcp error reason = ~p~n", [Reason]),
            gen_tcp:controlling_process(Socket, From),
            From!{cmd, close};         	 
        _ -> 
            log4erl:error("controller received unexpected request~n"),
            From!{cmd, close} 
    end.
loop_timeout(Loop)->
    Loop!{cmd, timeout}.
%%
%% Tests
%%
-include_lib("eunit/include/eunit.hrl").
-ifdef(TEST).
-endif.
